<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-check" @click="enable">启用</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-error" @click="disable">禁用</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="id" label="ID" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="url" label="url"align="center" width="80" sortable>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" min-width="160" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="父菜单" align="center" min-width="160" sortable>
      </el-table-column>
      <el-table-column label="操作" header-align="center" min-width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面
    :visible.sync="outerVisible" 新版本打开对话框
    v-model="menuFormVisible" 老版本打开对话框
    -->
    <el-dialog title="新增或修改" :visible.sync="menuFormVisible" :close-on-click-modal="false">
      <el-form :model="menu" label-width="80px" :rules="menuFormRules" ref="menuForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="menu.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="访问地址">
          <el-input type="label" v-model="menu.url"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input type="label" v-model="menu.icon"></el-input>
        </el-form-item>
        <el-form-item label="父菜单">
          <el-cascader v-model="menu.parent.id"
                       :options="topMenus"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
          ></el-cascader>
<!--          <select name="type" v-model="menu.parent.id" class="form-control" id="type">-->
<!--            <option value="-1">&#45;&#45;请选择&#45;&#45;</option>-->
<!--            <option v-for="m in topMenus" :value="m.id">{{m.name}}</option>-->
<!--          </select>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="menuFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="menuLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //分页相关
      query:{
        currentPage:1,
        pageSize:10,
        keyword:''
      },
      pageInfo:{
        total:0,
        rows:[]
      },
      listLoading: false,
      sels: [],//列表选中列

      menuid: null,
      menuname: '',
      menuFormVisible: false,//新增界面是否显示
      menuLoading: false,
      menuFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      //新增界面数据
      menu: {
        id:null,
        name:'',
        url:'',
        icon:'',
        parent:{}
      },
      employees:[],
      topMenus:[],
    }
  },
  methods: {
    getTopMenus(){
      this.$http.get("/menu/top")
          .then(result=>{
            this.topMenus = result.data;
            console.log(this.topMenus);
          })
    },
    // this.$router.push({ path: '/authorizeMenu' }); //跳转主页
    handleAuthorize(index, row){
      const {href} = this.$router.resolve({
        path: '/authorizeMenu',   //name-params    path-query
        query: {
          menuid: row.id,
          menuname: row.name
        }
      });
      window.open(href,'_blank')
    },
    enable(){
      var rowData = this.sels;
      this.$confirm('确认启用选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        for (let i = 0; i < rowData.length; i++) {
          rowData[i].state = 0;
        }
        console.log(rowData);
        this.$http.patch("/menu/enable",rowData).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '启用成功',
            type: 'success'
          });
          this.getMenus();
        });
      }).catch(() => {
      });
    },
    disable(){
      var rowData = this.sels;
      this.$confirm('确认启用选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        for (let i = 0; i < rowData.length; i++) {
          rowData[i].state = -1;
        }
        console.log(rowData);
        this.$http.patch("/menu/disable",rowData).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '禁用成功',
            type: 'success'
          });
          this.getMenus();
        });
      }).catch(() => {
      });
    },
    search(){
      //重置当前页为第一页
      this.query.currentPage =1;
      this.getMenus();
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      this.query.currentPage= val;
      this.getMenus();
    },
    //获取用户列表
    getMenus() {
      this.listLoading = true; //发起请求之前显示加载条
      //发起请求获取数据
      this.$http.post("/menu",this.query)
          .then(result =>{
            result = result.data; //{success,result:{}}
            if (result.success){
              this.pageInfo = result.data;
            }else{
              this.$message({
                message: '获取分页数据失败！'+result.message,
                type: 'error'
              });
            }
            this.listLoading = false;
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = row.id;
        this.$http.delete("/menu/"+para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getMenus();
        });
      }).catch(() => {
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getTopMenus(); //查询父级
      this.menuFormVisible = true;
      this.menu = Object.assign({}, row); //回显
      if(this.menu.parent==null){
        this.menu.parent={id: -1}
      }
      console.log(this.menu.parent);
      let path = this.menu.path; //包含自己/ 1/4/20
      if (path){
        let paths = path.split("/"); //["",1,4,20]
        let idsStr = paths.slice(1,paths.length-1);//[1,4]
        let idsInt = [];
        for (let i = 0; i <idsStr.length ; i++) {
          idsInt.push(parseInt(idsStr[i]));
        }
        //做部门的回显
        this.menu.parent = idsInt;
      }

    },
    //显示新增界面
    handleAdd: function () {
      this.menuFormVisible = true;
      this.menu =  {
        id:null,
        name:'',
        url:'',
        icon:'',
        parent:{id:-1}
      }
      this.getTopMenus(); //查询父级
    },
    //编辑
    save: function () {
      this.$refs.menuForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.menuLoading = true;
            let para = Object.assign({}, this.menu);
            this.$http.put("/menu",para).then((res) => {
              res = res.data;

              if (res.success){
                this.$message({
                  message: '保存成功',
                  type: 'success'
                });

                this.menuFormVisible = false; //关闭对话框

                this.$refs['menuForm'].resetFields(); //重置表单

                this.getMenus(); //重新加载数据
              }else{
                this.$message({
                  message: '保存失败,'+res.message,
                  type: 'error'
                });
              }

              this.menuLoading = false; //关闭加载条
            });
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/menu/batch",ids).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getMenus();
        });
      }).catch(() => {
      });
    }
  },
  mounted() {
    this.getMenus();
  }
}
</script>
